package com.springboot.study.controller;
import com.springboot.study.pojo.UserInfo;
import com.springboot.study.Repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * 测试用控制器，模拟新增用户操作
 */
@RestController
@RequestMapping("/userinfotest")
public class UserInfoTestController {
    @Autowired
    private UserInfoRepository userInfoRepository;
    /**
     * 测试新增用户接口，直接在服务器端创建一个用户并保存
     * */
    @GetMapping("/createUserTest")
    public String createUserTest() {
        // 使用for循环创建多个用户插入数据库
        for (int i = 1; i <= 500; i++) {
            UserInfo user = new UserInfo();
            user.setUsername("testuser" + i);
            user.setPassword("123456");
            user.setEmail("testuser" + i + "@example.com");
            user.setPhone("1234567890");
            UserInfo savedUser = userInfoRepository.save(user);
        }
        return "新增用户成功";
    }

    // 在插入的操作基础之上进行优化，如果信息已经存在那么就进行记录不在插入
    @GetMapping("/createUserinfotest_2")
    public String createUserinfotest_2() {
        for (int i = 1; i <= 500; i++) {
            String username = "testuser" + i;
            // 先查找是否存在该用户名
            if (userInfoRepository.findByUsername(username).isPresent()) {
                // 如果存在，跳过插入
                continue;
            }
            UserInfo user = new UserInfo();
            user.setUsername(username);
            user.setPassword("123456");
            user.setEmail(username + "@example.com");
            user.setPhone("1234567890");
            userInfoRepository.save(user);
        }
        return "新增用户成功（跳过重复用户名）";
    }

    // 写一个测试，查看所有的用户信息
    @GetMapping("/getAllUsers")
    public String getAllUsers() {
        return userInfoRepository.findAll().toString();
    }

    // 根据Id查询用户
    @GetMapping("/getUserById/{id}")
    public String getUserById(@PathVariable  Long id) {
        return userInfoRepository.findById(id).toString();
    }

    // 根据username查询用户
    @GetMapping("/getUserByUsername/{username}")
    public ResponseEntity<?> getUserByUsername(@PathVariable String username) {
        Optional<UserInfo> userOpt = userInfoRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            return ResponseEntity.ok(userOpt.get());
        } else {
            return ResponseEntity.status(404).body("User not found with username: " + username);
        }
    }

    // 根据email查询用户
    @GetMapping("/getUserByEmail/{email}")
    public ResponseEntity<?> getUserByEmail(@PathVariable String email) {
        Optional<UserInfo> userOpt = userInfoRepository.findByEmail(email);
        if (userOpt.isPresent()) {
            return ResponseEntity.ok(userOpt.get());
        } else {
            return ResponseEntity.status(404).body("User not found with email: " + email);
        }
    }

    // 根据phone查询用户
    @GetMapping("/getUserByPhone/{phone}")
    public ResponseEntity<?> getUserByPhone(@PathVariable String phone) {
        Optional<UserInfo> userOpt = userInfoRepository.findByPhone(phone);
        if (userOpt.isPresent()) {
            return ResponseEntity.ok(userOpt.get());
        } else {
            return ResponseEntity.status(404).body("User not found with phone: " + phone);
        }
    }

    // 删除用户
    @DeleteMapping("/deleteUser/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        if (!userInfoRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        userInfoRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    // 测试用：通过GET请求删除用户（仅测试，不推荐生产环境使用）
    @GetMapping("/deleteUser2/{id}")
    public ResponseEntity<Void> deleteUser2(@PathVariable Long id) {
        if (!userInfoRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        userInfoRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }

}
